<template>
	<div class="app-container bigScreen">
		<div class="header">
			<div class="back" @click="back">返回管理界面</div>
			<h1>今日排班</h1>
		</div>
		<div class="today_list">
			<div class="clearfix" style="padding: 0 10px;">
				<div class="clearfix" style="position: relative;">
					<div class="header_time_item" style="opacity: 0;">
						<!-- 					<span style="margin-bottom: 10px;" class="demonstration">请设置上哨准备时间(分钟) 目前 {{ readyTime }} 分钟</span>
						<el-slider v-model="readyTime" :step="5" :max="40" show-stops></el-slider> -->
					</div>

					<div class="schedulingTaskTime  center_timer" style="float: right;line-height: 40px;width: 300px;display: flex;justify-content: space-around;">
						<span>{{ date }}</span>
						<span>{{ currentTime }}</span>
						<span>{{ week }}</span>
					</div>

					<div style="float: right;">
						<el-time-picker
							is-range
							format="HH:mm"
							v-model="timeRange"
							range-separator="至"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							placeholder="选择时间范围"
						></el-time-picker>
						<el-button style="margin-left: 10px;" type="primary" @click="add">插入排班时间</el-button>
					</div>
				</div>
			</div>

			<div class="schedulingTask_wrap">
				<div class="schedulingTask" style="background:rgba(19, 25, 47, 0.6);min-width: 1200px;">
					<div class="table" style="border-bottom: 1px solid rgba(4,6,14,1);">
						<div class="tableList completeTime"><div class="tableItem" style="color: #fff;cursor: pointer;">哨位</div></div>
						<div class="tableList completeTime" v-for="(item, index) in currentTimeArr">
							<div class="oper" v-if="item">
								<el-popover v-if="index >= 2" placement="bottom" width="400" ref="popover" trigger="click">
									<div>
										<el-time-picker
											is-range
											v-model="timeRange"
											format="HH:mm"
											setp="1:00"
											range-separator="至"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
											@change="edit($event, item)"
											placeholder="选择时间范围"
										></el-time-picker>
									</div>
									<el-button type="primary" slot="reference" style="transform: scale(.7);" icon="el-icon-edit" circle></el-button>
								</el-popover>
								<div class="tableItem" style="color: #fff;cursor: pointer;">{{ item }}</div>

								<el-popconfirm v-if="index >= 2" title="确定删除吗" @confirm="del(item, index)">
									<el-button type="danger" slot="reference" style="transform: scale(.7);" icon="el-icon-delete" circle></el-button>
								</el-popconfirm>
							</div>
						</div>
					</div>
					<div class="table" :class="index % 2 == 0 ? 'act' : ''" v-for="(item, index) in SchedulingDayList.sentryPostList">
						<div class="schedulingDataList tableList">
							<div class="tableItem" style="color: #fff;font-weight:bold;cursor: pointer;">
								<div>{{ item.sentryPostName }}</div>
							</div>
						</div>

						<div class="tableList completeTime">
							<div class="tableItem" style="color: #fff;cursor: pointer;">
								<div>{{ SchedulingDayList.data[PeriodTimeIndex - 2] | sentry(index) }}</div>
							</div>
						</div>
						<div class="tableList completeTime">
							<div class="tableItem" style="color: #fff;cursor: pointer;">
								<div>{{ SchedulingDayList.data[PeriodTimeIndex - 1] | sentry(index) }}</div>
							</div>
						</div>
						<div class="tableList">
							<draggable
								class="tableItem"
								v-if="SchedulingDayList.data[PeriodTimeIndex]"
								:list="SchedulingDayList.data[PeriodTimeIndex][index]"
								:group="{ name: 'people', pull: pullFunction }"
								@change="log($event, index, PeriodTimeIndex)"
								sort="true"
								style="color: #FF0000;"
							>
								<div>{{ SchedulingDayList.data[PeriodTimeIndex] | sentry(index) }}</div>
							</draggable>
						</div>
						<div class="tableList">
							<draggable
								class="tableItem"
								v-if="SchedulingDayList.data[PeriodTimeIndex + 1]"
								:list="SchedulingDayList.data[PeriodTimeIndex + 1][index]"
								:group="{ name: 'people', pull: pullFunction }"
								@change="log($event, index, PeriodTimeIndex + 1)"
								style="color:  #33cea0;"
							>
								<div>{{ SchedulingDayList.data[PeriodTimeIndex + 1] | sentry(index) }}</div>
							</draggable>
						</div>
						<div class="tableList">
							<draggable
								v-if="SchedulingDayList.data[PeriodTimeIndex + 2]"
								class="tableItem"
								:list="SchedulingDayList.data[PeriodTimeIndex + 2][index]"
								:group="{ name: 'people', pull: pullFunction }"
								@change="log($event, index, PeriodTimeIndex + 2)"
								style="color:  #33cea0;"
							>
								<div>{{ SchedulingDayList.data[PeriodTimeIndex + 2] | sentry(index) }}</div>
							</draggable>
						</div>
					</div>
				</div>

				<div class="sendPost">
					<div class="topContent" style="padding: 10px 5px;">
						<div class="selectList" v-for="(item, index) in selectList" :key="index">
							<div class="person_box" @mouseover="showDelBtn(index)" @mouseout="hideDelBtn(index)" @click="removeSelect(index)">
								<div class="del" v-show="item.show"><i class="el-icon-delete"></i></div>
								<el-avatar :size="60" icon="el-icon-user-solid" :src="item.picture | baseImg"></el-avatar>
								<div style="padding: 5px; ">
									<span>{{ item.name }}</span>
								</div>
							</div>
						</div>
					</div>
					<div class="inputContent">
						<el-row>
							<el-col :span="18"><el-input v-model="message" placeholder="请输入内容"></el-input></el-col>
							<el-col :span="6"><el-button style="float: right;" type="primary" @click="send">呼叫</el-button></el-col>
						</el-row>
					</div>
				</div>
			</div>

			<div class="personList" style="position: relative;height: 30vh;overflow-y: scroll;">
				<div class="list-group">
					<div class="className" v-for="(item, index) in personList">
						<div class="className_title">{{ item.className }}</div>
						<draggable class="list-group" :list="item.shortPersonList" :group="{ name: 'people', pull: pullFunction }">
							<div
								class="person_box"
								v-for="(item2, index2) in item.shortPersonList"
								:class="selectList.findIndex(v => v.id == item2.id) >= 0 ? 'act' : ''"
								@click="choosePerson(item2, index2)"
							>
								<el-avatar :size="60" icon="el-icon-user-solid" :src="item2.picture | baseImg"></el-avatar>
								<div style="padding: 5px; ">
									<span>{{ item2.name }}</span>
								</div>
							</div>
						</draggable>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { getSchedulingDay, editScheduling, manualSend } from '@/api/tranShort/scheduling';
import { getPersonGroupClassGrade } from '@/api/tranShort/person';
import draggable from '@/vuedraggable';
import dayjs from 'dayjs';
let week_arr = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
let isBetween = require('dayjs/plugin/isBetween');
dayjs.extend(isBetween);

export default {
	data() {
		return {
			loading: true,
			date: '', //日期
			week: '', //星期
			controlOnStart: true,
			// time:'',
			week_arr: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
			SchedulingDayList: [],
			sentryPostList: [],
			// 查询参数

			currentTime: dayjs().format('HH:mm:ss'), // 获取当前时间,
			personList: [],
			message: '',
			PeriodTime: '', //当前时间处于的时间段
			PeriodTimeIndex: '',
			timeQuantum: [],
			currentTimeArr: [],
			schedulingDateId: '',
			timeRange: [],
			selectList: [],
			readyTime: 15,
			_personList: []
		};
	},
	components: {
		draggable
	},

	mounted() {
		// // dayjs
		const loading = this.$loading({
			lock: true,
			text: 'Loading'
		});
		setTimeout(() => {
			loading.close();
		}, 2000);
		this.initWebSocket();
		setInterval(() => {
			this.currentTime = dayjs().format('HH:mm:ss'); //修改数据让他可以实时更新
		}, 1000);

		let date = dayjs();
		this.date = date.format('YYYY-MM-DD');
		this.week = week_arr[date.day()];

		let d = date.format('YYYY-MM-DD') + ' ' + '23:59';
		this.timeRange = [new Date(), d];
		this.getschedulingDay();

		this.getList();

		// setTimeout(v=>{
		// this.edit([new Date(),new Date('2021-09-19 16:00:00')],"23:4-23:59")
		// },2000)
	},
	filters: {
		sentry(arr, index) {
			if (!arr) return '无';
			if (!arr[index]) return '';
			return arr[index].map(v => v.name).join();
		},
		baseImg(url) {
			if (!url) return '';
			if (!url.startsWith('http')) {
				return process.env.VUE_APP_BASE_API + url;
			} else {
				return url;
			}
		}
	},
	methods: {
		showDelBtn(index) {
			this.selectList[index].show = true;
		},
		hideDelBtn(index) {
			this.selectList[index].show = false;
		},
		removeSelect(index) {
			this.selectList.splice(index, 1);
		},
		back() {
			this.$router.replace({
				path: '/'
			});
		},
		add(e) {
			let { schedulingDateId, sentryPostList } = this;
			sentryPostList = sentryPostList.map(v => {
				return v.id;
			});
			let timeQuantum = this.timeRange
				.map(v => {
					if (typeof v != 'object') {
						v = new Date(v);
					}
					return v.getHours() + ':' + v.getMinutes();
				})
				.join('-');
			editScheduling({
				type: 'addTime',
				schedulingDateId,
				sentryPostIdList: sentryPostList,
				timeQuantum
			}).then(res => {
				console.log(res);

				if (res.code == 200) {
					this.$message.success(res.msg);
					this.reset();
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		del(timeQuantum, index) {
			let { schedulingDateId, sentryPostList } = this;

			sentryPostList = sentryPostList.map(v => {
				return v.id;
			});
			editScheduling({
				type: 'deleteTime',
				timeQuantum: timeQuantum,
				schedulingDateId,
				sentryPostIdList: sentryPostList
			}).then(res => {
				if (res.code == 200) {
					this.$message.success(res.msg);
					this.reset();
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		edit(e, timeQuantum) {
			let newTimeQuantum = e
				.map(v => {
					return v.getHours() + ':' + v.getMinutes();
				})
				.join('-');

			let { schedulingDateId } = this;
			editScheduling({
				type: 'editTime',
				schedulingDateId,
				newTimeQuantum,
				oldTimeQuantum: timeQuantum
			}).then(res => {
				if (res.code == 200) {
					this.$message.success(res.msg);
					this.reset();
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		// 获取区间时间
		countDownTime(timeArr) {
			let now = new Date().getTime();

			let index = timeArr.findIndex(v => {
				return now >= v.start && now < v.end;
			});
			let time = this.timeQuantum;
			let currentTimeArr = [-2, -1, 0, 1, 2].map(v => {
				return time[index + v];
			});
			this.currentTimeArr = currentTimeArr;

			if (this.PeriodTimeIndex !== index && index == -1) {
				setTimeout(v => {
					this.reset();
				}, 10000);
				return;
			}

			this.PeriodTimeIndex = index;

			setTimeout(v => {
				this.countDownTime(timeArr);
			}, 10000);
		},
		//重置
		reset() {
			let date = dayjs();
			this.date = date.format('YYYY-MM-DD');
			this.week = week_arr[date.day()];

			this.getschedulingDay();
			// window.location.reload()
			return;
		},

		/** 查询哨位管理列表 */
		getschedulingDay() {
			this.loading = true;
			getSchedulingDay().then(response => {
				console.log(response);
				this.SchedulingDayList = response.data;
				this.timeQuantum = response.data.timeQuantum;

				// .map(v=>{

				// return 	v.split('-').map(v2=>{
				// 	 let [,m]	 = v2.split(':');
				// 	 if(m.length==1){
				// 		 v2 = v2+'0'
				// 	 }
				// 	 return v2

				// 	}).join('-')

				// });
				this.loading = false;
				this.schedulingDateId = response.data.schedulingDateId;
				this.sentryPostList = response.data.sentryPostList;
				let { date } = this;

				let _timeQuantum = this.timeQuantum.map(v => {
					let [start, end] = v.split('-');
					start = new Date(date + ' ' + start).getTime();
					end = new Date(date + ' ' + end).getTime();
					return {
						start,
						end
					};
				});
				console.log(_timeQuantum);

				//  计算 并减少时间
				this.countDownTime(_timeQuantum);
			});
		},
		// 获取人员列表
		getList() {
			// this.loading = true;
			getPersonGroupClassGrade().then(response => {
				console.log(response);
				this.personList = response.data;
				// this.total = response.total;
				let list = [];
				// this.loading = false;
				this.personList.forEach(v => {
					list.push(...v.shortPersonList);
				});

				this._personList = list;
			});
		},
		pullFunction() {
			return 'clone';
		},
		log(e, index, index2) {
			this.$forceUpdate();

			console.log(this.SchedulingDayList.data[index2]);
			let { timeQuantum, schedulingDateId, sentryPostList } = this;
			let personData = this.SchedulingDayList.data[index2][index].map(v => {
				return v.id;
			});

			editScheduling({
				type: 'editPerson',
				schedulingDateId,
				sentryPostId: sentryPostList[index].id,
				timeQuantum: timeQuantum[index2],
				personData
			}).then(res => {
				if (res.code == 200) {
					this.$message.success(res.msg);
					this.reset();
				} else {
					this.$message.error(res.msg);
				}
			});
		},
		send() {
			let { message, selectList } = this;
			if (!message) {
				this.$message.info('请填写消息');
				return;
			}
			if (selectList.length == 0) {
				this.$message.info('请点击左侧选择人员');
				return;
			}

			// this.websocketsend('1');
			selectList = selectList.map(v => {
				return v.id;
			});
			manualSend({
				message,
				personIdList: selectList
			}).then(res => {
				console.log(res);
				this.$message.success('发送成功');
			});
		},
		choosePerson(item) {
			let index = this.selectList.findIndex(v => {
				return v.id === item.id;
			});
			if (index >= 0) {
				this.selectList.splice(index, 1);
			} else {
				item.show = false;
				this.selectList.push(item);
			}

			console.log(this.selectList);
		},
		initWebSocket() {
			//初始化weosocket
			// const wsuri = 'ws://' + location.host + process.env.VUE_APP_BASE_API + '/webSocket';
			const wsuri = 'ws://' + location.host + '/webSocket';
			this.websock = new WebSocket(wsuri);
			this.websock.onmessage = this.websocketonmessage;
			this.websock.onopen = this.websocketonopen;
			this.websock.onerror = this.websocketonerror;
			this.websock.onclose = this.websocketclose;
		},
		websocketonopen() {
			console.log('连接');
		},
		/**
		 * 连接建立失败,断开连接
		 * 1.查询一次数据库数据
		 * 2.查询完后再次建立socket连接
		 * */
		websocketonerror() {
			//连接建立失败重连

			//this.websock.onclose()
			setTimeout(v => {
				this.initWebSocket();
			}, 1000);
		},
		websocketonmessage(e) {
			//数据接收
			let redata = JSON.parse(e.data).deviceCode;
			redata.split(',').forEach(v => {
				let person = this._personList.find(item => {
					return v == item.shortWristbandDervice.derviceCode;
				});
				if (person) {
					this.$message.success(`${person.classGradeName}的${person.name}请准备上哨`);
				}
			});

			console.log(e);
		},
		websocketsend(Data) {
			//数据发送
			this.websock.send(Data);
		},
		websocketclose(e) {
			//关闭
			console.log('断开连接', e);
		}
	}
};
</script>

<style lang="scss" scoped="scoped">
.bigScreen {
	background: url('../assets/images/bg.png') no-repeat;
	background-size: 100% 100%;
	color: #fff;
	height: 100vh;
	overflow: hidden;
}

.header {
	width: 100%;
	height: 60px;
	color: #fff;
	// background: rgba(245, 250, 253, 1.0);
	position: relative;
	// top: 60px;
	// left: 0;
	text-align: center;
	z-index: 99;
	.back {
		position: absolute;
		left: 10px;
		top: 8px;
		cursor: pointer;
		padding: 10px;
	}

	h2 {
		color: #000;
	}

	.date {
		position: absolute;
		right: 20px;
		color: #000;
		bottom: 15px;
	}
}

.today_list {
	padding-top: 10px;
	position: relative;
	height: 66vh;
	.schedulingTask_wrap {
		overflow: hidden;
		padding: 0 20px;
		height: 50vh;
		overflow-y: scroll;
	}

	.schedulingTask {
		width: calc(100% - 500px);
		float: left;
		background: rgba(19, 25, 47, 0.6);
		padding: 10px 30px;
		margin: 20px auto;
		.schedulingTaskTime {
			display: flex;
			justify-content: space-between;
			padding: 0 10px;
			height: 30px;
			line-height: 30px;
			color: #fff;
			background-color: #0072c6;
		}
		.table {
			&.act {
				background-color: rgba(23, 28, 51, 1);
			}
			display: flex;
			justify-content: space-between;
			// width: 111%;
			// background-color: #ffffff;
			.tableList {
				margin: 1px;
				width: 17%;
				padding: 0 3px;
				// height: 200px;
				.tableItem {
					width: 100%;
					height: 50px;
					text-align: center;
					line-height: 50px;
					// background-color: #007256;
					cursor: move;
				}
				.oper {
					position: relative;
					color: #fff;
					cursor: pointer;
					height: 40px;
					display: flex;
					justify-content: space-between;
					padding: 0 10px;
				}
			}
		}
	}

	.headerTime {
		text-align: center;
		padding-right: 20px;

		.date {
			float: right;
		}

		span {
			margin: 0 20px;
		}
	}

	table {
		line-height: 30px;

		border-top: 1px solid #999;

		border-left: 1px solid #999;

		border-spacing: 0;

		thead th {
			border: none;
			padding: 0;

			&:first-child {
				text-align: left;
				padding-left: 20px;
			}
		}

		td {
			padding: 10px 30px;

			border-bottom: 1px solid #999;

			border-right: 1px solid #999;
		}
	}

	.sendPost {
		height: 430px;
		width: 430px;
		
		background-color: rgba(19, 25, 47, 0.7);
		position: absolute;
		right: 30px;
		top: 120px;
		z-index: 99;
		.topContent{
			height: 400px;
			overflow: scroll;
		}
		.inputContent {
			position: absolute;
			bottom: 0;
			height: 40px;
			width: 100%;
		}
	}

	.list-group {
		margin-top: 20px;
		width: 80%;
		cursor: move;
	}

	.person_box,
	.className_title {
		width: 80px;
		height: 100px;
		border-radius: 4px;
		float: left;
		overflow: hidden;
		color: #fff;
		text-align: center;
		font-size: 16px;
		border: 1px solid transparent;

		img {
			width: 60px;
			height: 60px;
		}
	}

	.person_box.act {
		border: 1px solid #13ce66;
	}
	.className_title {
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.className {
		width: 100%;
		overflow: hidden;
	}
	.header_time_item {
		width: 500px;
		float: left;
		padding: 10px 20px;
		height: 80px;
		position: relative;
		background: rgba(19, 25, 47, 0.6);
		border-radius: 5px;
	}
	.center_timer {
		position: absolute;
		top: 0;
		left: 50%;
		transform: translateX(-50%);

		margin: auto;
	}
}

::-webkit-scrollbar {
	width: 7px;
	height: 7px;
	background-color: rgba(23, 28, 51, 1);
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
	box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
	-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
	border-radius: 10px;
	background-color: rgba(23, 28, 51, 1);
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
	border-radius: 10px;
	box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
	-webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
	background-color: rgba(23, 28, 51, 0.9);
}
.person_box {
	position: relative;
	cursor: pointer;
	.del {
		position: absolute;
		width: 61px;
		height: 61px;
		left: 9px;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26px;
	}
}
</style>
